import re


def read_error_file_and_generate_sql(file_path):
    """
    读取error.txt文件，提取报错的changeset id并生成SQL语句
    """
    try:
        # 读取文件内容
        with open(file_path, 'r', encoding='utf-8') as file:
            error_log = file.read()

        # 正则表达式匹配changeset id（格式：文件名::id::作者）
        pattern = r'xuanzang-changelog\.xml::([^:]+)::[^\s]+ was: [^:]+:[^ ]+ but is now: ([^:]+:[^ ]+)'

        # 提取所有changeset id
        matches = re.findall(pattern, error_log)

        if not matches:
            print("未找到匹配的changeset id，请检查错误日志格式")
            return

        # 生成SQL语句
        sql_statements = []
        for changeset_id, correct_md5sum in matches:
            sql = f"UPDATE databasechangelog SET md5sum = '{correct_md5sum.strip()}' WHERE id = '{changeset_id}';"
            if sql not in sql_statements:
                sql_statements.append(sql)


        print("\n生成的SQL语句:")
        for sql in sql_statements:
            print(sql)

        print(f"\n总共找到 {len(sql_statements)} 个需要修复的changeset")

        # 可选：将SQL语句保存到文件
        save_to_file = input("\n是否将SQL语句保存到文件？(y/n): ")
        if save_to_file.lower() == 'y':
            output_file = 'fix_changeset_md5.sql'
            with open(output_file, 'w', encoding='utf-8') as f:
                for sql in sql_statements:
                    f.write(sql + '\n')
            print(f"SQL语句已保存到 {output_file}")

        return sql_statements

    except FileNotFoundError:
        print(f"错误：找不到文件 {file_path}")
    except Exception as e:
        print(f"读取文件时发生错误：{e}")


# 使用示例
if __name__ == "__main__":
    # 指定error.txt文件路径
    file_path = "error.txt"

    # 执行提取和生成
    read_error_file_and_generate_sql(file_path)